package cn.itcast.usermanage.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.itcast.usermanage.pojo.EasyUIResult;
import cn.itcast.usermanage.pojo.User;
import cn.itcast.usermanage.service.UserService;

@Controller
public class UserManager {
	@Autowired
	private UserService userService;
	
	@RequestMapping("users")
	public String test(){
		
		return "users";
	}
	//查询所有用户
	@RequestMapping("user/list")
	@ResponseBody
	public EasyUIResult queryUserList(@RequestParam("page") int page,@RequestParam("rows") int rows){
		
		return userService.queryUserAllByPage(page,rows);
	}
	
	//跳转用户添加页面
	@RequestMapping("/user/{page}")
	public String toPage(@PathVariable("page") String page){
		
		return page;
	}
	
	//添加用户
	@RequestMapping("/user/save")
	@ResponseBody
	public Map<String,Object> addUser(User user){
		Map<String,Object> map=new HashMap<>();
		int count=userService.addUser(user);
		//判断
		if(count>0){
			map.put("status", 200);
		}else{
			map.put("status", 500);
		}
		return map;
	}
	//修改用户
	@RequestMapping("/user/editUser")
	@ResponseBody
	public Map<String,Object> editUser(User user,@RequestParam("id") long id){
		Map<String,Object> map=new HashMap<>();
		user.setId(id);
		int count=userService.editUser(user);
		//判断
		if(count>0){
			map.put("status", 200);
		}else{
			map.put("status", 500);
		}
		return map;
	}
	
	//删除用户
		@RequestMapping("/user/delete")
		@ResponseBody
		public Map<String,Object> deleteUser(@RequestParam("ids") long[] ids){
			Map<String,Object> map=new HashMap<>();
			for (long id : ids) {
				int count=userService.deleteUserById(id);
				//判断
				if(count>0){
					map.put("status", 200);
				}else{
					map.put("status", 500);
				}
			}
		
			return map;
		}
	//根据id查询用户:
		@RequestMapping("/user/edit")
		public String editUser(@RequestParam("id") long id,Model model){
			
			
				User user=userService.queryUserById(id);
			
				model.addAttribute("user", user);
		
			return "userEdit";
		}
	//导出功能
		
		@RequestMapping("user/export/excel")
		
		public String export(@RequestParam("page") Integer page,@RequestParam("rows") Integer rows,Model model){
			EasyUIResult result= userService.queryUserAllByPage(page, rows);
			model.addAttribute("userList", result.getRows());
			return "userExcel";
			
		}
	
	
	
	
	

}
